package com.xx.ems.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.xx.ems.model.Accessory;
import com.xx.ems.model.Equipments;
import com.xx.ems.system.BaseController;

/**
 * @author xxx
 * @date 2014-2-26
 * @version 1.0
 * 描述: 设备(包括相应的附件)CRUD操作
 */
@Controller
@RequestMapping(value="equipmentCRUD",method=RequestMethod.POST)
public class EquipmentCRUDController extends BaseController {
	/**
	 * 描述: 添加设备及相应的附件 
	 * @param accessoryList
	 * @param modelmap
	 * @param response
	 * @date 2014-2-26
	 * 
	 * json格式：
	 * var accessoryArray = [];
	 * var equipment = {ename:"1212",eprice:"2323",enternum:"2"};   //将设备的数量作为设备的一个属性
	 * var accessory1 = {aname:"232",aprice:"23232",equipments:equipment};  //将equipment作为第一个附件的一个属性
	 * var accessory2 = {aname:"232"};
	 * accessoryArray.push(accessory1);
	 * accessoryArray.push(accessory2);
	 * $.ajax({
	 * 		url:"/ems/equipmentCRUD/addEquipment",
	 * 		type:"POST",
	 * 		data:JSON.stringify(accessoryArray),
	 * 		dataType:"json",
	 * 		contentType:"application/json; charset=utf-8",
	 * 		success:function(data){
	 * 			alert(data.result);
	 * 		}
	 * });
	 */
	@RequestMapping(value="/addEquipment")
	public void addEquipment(@RequestBody List<Accessory> accessoryList, HttpServletResponse response){
		try{
			/**
			 * 获取设备对象
			 */
			Equipments equipment = accessoryList.get(0).getEquipments();
			/**
			 * 获取设备的数量
			 */
			int enterNum = equipment.getEnternum();
			List<Integer> eidarray = getEquipmentCRUDService().addEquipment(enterNum, equipment, accessoryList);
			JSONObject json = new JSONObject();
			response.setContentType("application/json");
			if (eidarray != null) {
				json.put("result", "suc");
				json.put("eidarray", eidarray);
			}else {
				json.put("result", "fail");
			}
			response.getWriter().println(json.toString());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 描述: 修改设备及相应的附件 
	 * @param accessoryList
	 * @param response
	 * @param modelmap
	 * @date 2014-2-26
	 */
	@RequestMapping(value="/updateEquipment")
	public void updateEquipment(@RequestBody List<Accessory> accessoryList, HttpServletResponse response){
		try{
			/**
			 * 获取设备对象
			 */
			Equipments equipment = accessoryList.get(0).getEquipments();
			boolean result = getEquipmentCRUDService().updateEquipment(equipment, accessoryList);
			JSONObject json = new JSONObject();
			response.setContentType("application/json");
			if (result) {
				json.put("result", "suc");
			}else {
				json.put("result", "fail");
			}
			response.getWriter().println(json.toString());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 描述: 删除设备 (暂时不提供) 
	 * @param eids
	 * @param response
	 * @date 2014-2-26
	 */
	@RequestMapping(value="/deleteEquipment")
	public void deleteEquipment(int[] eids, HttpServletResponse response){
		try{
			boolean result = getEquipmentCRUDService().deleteEquipment(eids);
			JSONObject json = new JSONObject();
			response.setContentType("application/json");
			if (result) {
				json.put("result", "suc");
			}else {
				json.put("result", "fail");
			}
			response.getWriter().println(json.toString());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 描述: 删除附件 
	 * @param aids
	 * @param response
	 * @date 2014-2-26
	 */
	@RequestMapping(value="/deleteAccessory")
	public void deleteAccessory(String aids, HttpServletResponse response){
		try{
			boolean result = getEquipmentCRUDService().deleteAccessory(aids);
			JSONObject json = new JSONObject();
			response.setContentType("application/json");
			if (result) {
				json.put("result", "suc");
			}else {
				json.put("result", "fail");
			}
			response.getWriter().println(json.toString());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 描述: 上传设备图片 
	 * @param eids
	 * @param file
	 * @param response
	 * @throws Exception 
	 * @date 2014-3-2
	 * 
	 * html要引入ajaxfileupload.js
	 * json格式：
	 * $.ajaxFileUpload({
	 * 		url:"/ems/equipmentCRUD/uploadEquipmentImg",
	 * 		secureuri:false,  //一般设置为false
	 * 		fileElementId:"file",  //文件上传空间的id属性  <input type="file" id="file" name="file" />
	 * 		dataType:"json",
	 * 		success: function (data, status){
	 * 			alert(data.result);
	 * 		},
	 * 		error: function (data, status, e){
	 * 			alert(e);
	 * 		}
	 * });
	 */
	@RequestMapping(value="/uploadEquipmentImg")
	public void uploadEquipmentImg(String eids, HttpServletRequest request, HttpServletResponse response) throws Exception{
		JSONObject json = new JSONObject();
		response.setContentType("text/html");
		try {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				/**
				 * 获取上传到服务器的文件绝对路径
				 */
				String directory = "/eimg";
				String targetDirectory = request.getSession().getServletContext().getRealPath(directory);
				String fileName = null;
				/**
				 * 获取上传的图片文件名称
				 */
				Iterator<String> it = multiRequest.getFileNames();
				while (it.hasNext()) {
					/**
					 * 获取上传的文件
					 */
					MultipartFile file = multiRequest.getFile(it.next());
					/**
					 * 改写上传的文件名称
					 */
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
					fileName = sdf.format(Calendar.getInstance().getTime()) + file.getOriginalFilename();
					/**
					 * 将上传的文件放到服务器指定的位置
					 */
					File uploadFile = new File(targetDirectory, fileName);
					file.transferTo(uploadFile);
				}
				/**
				 * 获取设备的id集合
				 */
				String[] eidArray = eids.split(",");
				List<Integer> eidList = new ArrayList<Integer>();
				for (String eid : eidArray) {
					eidList.add(Integer.valueOf(eid));
				}
				/**
				 * 将录入的设备与相应的图片进行绑定 
				 */
				getEquipmentCRUDService().bindEimgWithEquipment(eidList, "/ems"+directory+"/"+fileName);
			}
			json.put("result", "suc");
		}catch(Exception e) {
			e.printStackTrace();
			json.put("result", "fail");
		}finally{ 
			response.getWriter().println(json.toString());
		}
	}
	
	/**
	 * 描述: 批量录入设备 (excel上传)  暂未实现 
	 * @param file
	 * @date 2014-3-2
	 */
	@RequestMapping(value="/batchEnteringEquipment")
	public void batchEnteringEquipment(@RequestParam("file") CommonsMultipartFile file){
		System.out.println(file.getOriginalFilename());
	}
	
	/**
	 * 描述: 获取设备列表 
	 * @param response
	 * @date 2014-3-3
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/getEquipementList")
	public void getEquipementList(@RequestParam(defaultValue="1") int pageNow, @RequestParam(defaultValue="8") int maxCount, HttpServletResponse response) {
		try{
			Map<String, Object> map = getEquipmentCRUDService().getEquipmentList(pageNow, maxCount);
			JSONObject json = new JSONObject();
			response.setContentType("application/json");
			List<Object> list = (List<Object>) map.get("list");
			if (list.size() > 0) {
				json.put("result", list);
			}else {
				json.put("result", "empty");
			}
			json.put("pageNow", pageNow);
			json.put("totalpage", map.get("totalpage"));
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println(json.toString());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 描述: 根据设备id获取相应的附件信息 
	 * @param eid
	 * @param response
	 * @date 2014-3-3
	 */
	@RequestMapping(value="/getAccessoryByEquipmentId")
	public void getAccessoryByEquipmentId(int eid, HttpServletResponse response) {
		try{
			List<Object> list = getEquipmentCRUDService().getAccessoryByEquipmentId(eid);
			JSONObject json = new JSONObject();
			response.setContentType("application/json");
			if (list.size() > 0) {
				json.put("result", list);
			}else {
				json.put("result", "empty");
			}
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println(json.toString());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 描述: 根据设备名或设备编号进行模糊查询 
	 * @param searchinfo
	 * @param pageNow
	 * @param maxCount
	 * @param response
	 * @date 2014-3-4
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/getEquipmentListByEnumberOrEname")
	public void getEquipmentListByEnumberOrEname(String searchinfo, @RequestParam(defaultValue="1") int pageNow, @RequestParam(defaultValue="8") int maxCount, HttpServletResponse response) {
		try{
			Map<String, Object> map = getEquipmentCRUDService().getEquipmentListByEnumberOrEname(searchinfo, pageNow, maxCount);
			JSONObject json = new JSONObject();
			response.setContentType("application/json");
			List<Object> list = (List<Object>) map.get("list");
			if (list.size() > 0) {
				json.put("result", list);
			}else {
				json.put("result", "empty");
			}
			json.put("pageNow", pageNow);
			json.put("totalpage", map.get("totalpage"));
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println(json.toString());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 描述: 根据条件查询获得符合条件的设备列表 (报表) 
	 * @param response
	 * @param pageNow
	 * @param maxCount
	 * @param equipment
	 * @param eprice2
	 * @param in_time2
	 * @param produced_date2
	 * @param deadline2
	 * @param buy_time2
	 * @date 2014-3-6
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/getEquipmentListByCriteriaQuery")
	public void getEquipmentListByCriteriaQuery(HttpServletResponse response, int pageNow, int maxCount, Equipments equipment, double eprice2, Date in_time2, Date produced_date2, int deadline2, Date buy_time2) {
		try{
			Map<String, Object> map = getEquipmentCRUDService().getEquipmentListByCriteriaQuery(pageNow, maxCount, equipment, eprice2, in_time2, produced_date2, deadline2, buy_time2);
			JSONObject json = new JSONObject();
			response.setContentType("application/json");
			List<Object> list = (List<Object>) map.get("list");
			if (list.size() > 0) {
				json.put("result", list);
			}else {
				json.put("result", "empty");
			}
			json.put("pageNow", pageNow);
			json.put("totalpage", map.get("totalpage"));
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println(json.toString());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}